import AuthComponent from '@/components/Authorized/AuthComponent';
import { Button, Menu, Modal, Select, Popover, message } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import ProTable from '@ant-design/pro-table';
import styles from './index.less';

import { fileDownload } from '@/utils/downExcel';

import {
  getCountryRoute,
  updateCountryRoute,
  deleteCountryRoute
} from './service.js'
import HeaderDropdown from '@/components/HeaderDropdown';
import { DownOutlined } from '@ant-design/icons';
import RouteMaintenance from './components/RouteMaintenance';

const MenuItem = Menu.Item;
const { confirm: ModalConfirm, info: ModalInfo } = Modal;
const { Option } = Select;

export default () => {

  const actionRef = useRef();
  const ref = useRef();

  const [height, controlH] = useState(300); // table高度
  const [isCollapse, controlC] = useState(true);

  const [categoryList, setCategoryList] = useState([]); // 供应商查询列表

  const [choiceSupplier, setChoiceSupplier] = useState(null);
  const [choiceSupplierShow, setChoiceSupplierShow] = useState(false);

  const { run: updateCountryRouteRun } = useRequest(updateCountryRoute, {
    manual: true,
    onSuccess: res => {
      message.success(choiceSupplierShow === 'add' ? '新增成功' : '编辑成功');
      setChoiceSupplierShow(false);
      actionRef.current.reload();
      handleSelectedRowKeys([])
    }
  })

  // 删除
  const { run: deleteCountryRouteRun } = useRequest(deleteCountryRoute, {
    manual: true,
    onSuccess: res => {
      message.success('删除成功');
      actionRef.current.reload();
      handleSelectedRowKeys([])
    }
  })
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 347);
    } else {
      controlH(document.body.clientHeight - 482);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isCollapse])

  useEffect(() => {
    !choiceSupplierShow && setChoiceSupplier(null);
  }, [choiceSupplierShow])

  // 查询标签树
  // const { data } = useRequest(getTree);
  const data = [];

  // 删除
  const deleteProduct = id => {
    ModalConfirm({
      title: '提示',
      content: '确认删除吗？',
      onOk: () => {
        deleteCountryRouteRun(id);
      }
    })
  }

  const beforeSearchSubmit = params => {
    return params;
  }

  // // 操作菜单
  // const overlayMenu = row => {
  //   return (
  //     <Menu>
  //       <MenuItem>
  //         {/* <AuthComponent authCode="serviceQuality.PassengerTag.delete"> */}
  //         <Button type="link" onClick={() => deleteProduct(row)}>删除</Button>
  //         {/* </AuthComponent> */}
  //       </MenuItem>
  //     </Menu>
  //   )
  // };

  const columns = [
    // {
    //   title: '操作',
    //   dataIndex: 'id',
    //   hideInSearch: true,
    //   render: (_, row) => (
    //     <HeaderDropdown
    //       arrow={true}
    //       trigger={['hover']}
    //       overlay={() => overlayMenu(row)}
    //     >
    //       <Button type="link" onClick={() => { setChoiceSupplierShow('edit'); setChoiceSupplier(row);console.log(row) }}>
    //         <span>编辑</span>
    //         <DownOutlined />
    //       </Button>
    //     </HeaderDropdown>
    //   ),
    // },
    {
      title: '国家',
      dataIndex: 'country'
    },
    {
      title: '航站',
      dataIndex: 'terminalCode'
    },
    {
      title: '货币',
      dataIndex: 'currency',
      render: (_, row) => {
        return (
          <Popover content={_}>
            <span className={styles.emailStyles}>{_}</span>
          </Popover>
        )
      }
    }
  ];

  const save = e => {
    console.log(e);
    updateCountryRouteRun({
      ...choiceSupplier,
      country: e.country,
      currency: e.currency,
      terminalCode: (e.terminal.filter(item => item).map(item => item + '')).join(',')
    });
  }
  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选列
  // 选中添加值
  const tableSelectChange = (selectedRowKeys, selectedRows) =>{
    handleSelectedRowKeys(selectedRowKeys)
    handleSelectedRows(selectedRows)
  }
  // 设置选中的值
  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };

  return (
    <>
      <Modal
        title={choiceSupplierShow === 'add' ? '新增' : '编辑'}
        visible={Boolean(choiceSupplierShow)}
        destroyOnClose="true"
        maskClosable="true"
        onCancel={() => setChoiceSupplierShow(false)}
        footer={null}
      >
        {choiceSupplierShow && <RouteMaintenance choiceSupplier={choiceSupplier} save={save} onCancel={() => setChoiceSupplierShow(false)} />}
      </Modal>
      <ProTable
        actionRef={actionRef}
        formRef={ref}
        rowKey="id"
        className={styles.compactTable}
        toolBarRender={() => [
          <div>
            <AuthComponent authCode="mkt.setting.CountryRoute.save">
              <Button type="primary" style={{marginRight:20}}  icon='plus' onClick={() => setChoiceSupplierShow('add')}>新增</Button>
            </AuthComponent>
            <AuthComponent authCode="mkt.setting.CountryRoute.save">
              <Button
              style={{marginRight:20}}
                icon='edit'
                onClick={() => {
                  if (selectedRowKeys.length === 0||selectedRowKeys.length >1 ) {
                    message.error("只能选择一条进行编辑的条目")
                  } else {
                    setChoiceSupplierShow('edit')
                    setChoiceSupplier(selectedRows[0])
                  }
                }}
                selectedKeys={[]}
              >编辑</Button>
         </AuthComponent>
         <AuthComponent authCode="mkt.setting.CountryRoute.delete">
           <Button
            icon='delete'
            style={{marginRight:20}}
            onClick={() => {
              if (selectedRowKeys.length === 0 ) {
                message.error("请选择删除的条目")
              } else {
                deleteProduct(selectedRows.map(item => item.id))
              }
            }}
            selectedKeys={[]}
          >删除</Button>
          </AuthComponent>
          </div>
         ]}
        request={params => {
          return getCountryRoute(params);
        }}
        tableAlertRender={false}
        columns={columns}
        rowSelection={rowSelection}
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        beforeSearchSubmit={beforeSearchSubmit}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
        }}
        scroll={{ x: 900, y: height }}
        search={{
          onCollapse: val => {
            controlC(val)
          },
          span: { //设置排列方式
            xs: 24,
            sm: 24,
            md: 6,
            lg: 6,
            xl: 6,
            xxl: 6,
          }
        }}
      >
      </ProTable>
    </>
  )
}
